﻿using Aliyun.OSS;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
using zhangmenren.IService;
using zhangmenren.Models;
using zhangmenren.Untils;
using zhangmenren.Models.Enums;

namespace zhangmenren.Areas.Admin.Controllers
{
	[Area(areaName: "Admin")]
	public class BannerController : ABaseController
	{
		private IBannerService bannerService;
		public BannerController(IBannerService _bannerService)
		{
			bannerService = _bannerService;
		}


		// GET: /<controller>/
		public IActionResult Index()
		{
			return View();
		}

		public IActionResult Add()
		{
			return View();
		}

		public async Task<string> GetBanner(int page = 1)
		{
			int total = 0;
			IEnumerable<BannerEntity> dataList = null;
			dataList = await bannerService.Selelct();
            dataList.All(p =>
            {
                p.TypeStr = EnumsHelp.GetDisplayName(p.Type);

                return true;
            });
			if (dataList.Any())
			{
				total = dataList.Count();
			}
			return JsonConvert.SerializeObject(new { code = "0", msg = "查询成功", data = dataList, count = total });

		}

		/// <summary>
		/// 添加banner图
		/// </summary>
		/// <returns>The add.</returns>
		/// <param name="entity">实体模型</param>
		[HttpPost]
		public JsonResult Add(BannerEntity entity)
		{
			if (entity != null)
			{
				var result = bannerService.Add(entity);
				return Json(new { State = "OK", Msg = "添加成功" });
			}
			return Json(new { State = "FAIL", Msg = "添加错误，请稍后重试。" });
		}


		/// <summary>
		/// 删除banner图
		/// </summary>
		/// <returns>The del.</returns>
		/// <param name="id">Identifier.</param>
		[HttpPost]
		public JsonResult Del(int id = 0)
		{
			if (id != 0)
			{
				var result = bannerService.Del(id);
				return Json(new { state = "ok", msg = "删除成功" });
			}
			return Json(new { state = "fail", msg = "标识错误" });
		}

		/// <summary>
		/// 更新banner状态
		/// </summary>
		/// <returns>The enabled.</returns>
		/// <param name="isEnabled">If set to <c>true</c> is enabled.</param>
		/// <param name="id">Identifier.</param>
		[HttpPost]
		public JsonResult IsEnabled(bool isEnabled, int id = 0)
		{
			if (id != 0)
			{
				var result = bannerService.EditState(id, isEnabled);
				return Json(new { code = 1, msg = "修改成功" });
			}
            return Json(new { code = 0, msg = "标识错误" });
        }

		// 上传文件。
		[HttpPost]
		public JsonResult UploadFilesAjax()
		{
			var files = Request.Form.Files;
			List<string> list = new List<string>();
			foreach (var file in files)
			{
                var type =UpLoadHelper.GetExtension(file.FileName); //file.ContentType.Substring(file.ContentType.LastIndexOf('/') + 1);
				var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + type;
				var ossurl = Config.OSSURL;
				var endpoint = Config.ENDPOINT;
				var accessKeyId = Config.AccessKeyID;
				var accessKeySecret = Config.AccessKeySecret;
				var bucketName = Config.BACKETNAME;
				var objectName = filename;
				var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
				try
				{
					var result = client.PutObject(bucketName, objectName, file.OpenReadStream());
					list.Add(ossurl + objectName);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Put object failed, {0}", ex.Message);
				}
			}
			return Json(new { code = 0, msg = "上传成功", data = new { src = string.Join(",", list.ToArray()) } });
		}



		//public JsonResult UploadImg(string prefixName, string folderName, int width = -1, int height = -1, int type = 0, string code = "")
		//{
		//	var file = Request.Form.Files[0];
		//	try
		//	{
		//		byte[] bt = UpLoadHelper.StreamToBytes(file.ContentDisposition);
		//		//判断上传图片的长宽
		//		Image image = Image.FromStream(file.InputStream);
		//		if (width != -1 || height != -1)
		//		{
		//			//判断比较图片类型
		//			if (type == 0)//固定图片大小
		//			{
		//				if (image.Width != width || image.Height != height)
		//					return Json(new ResultMsg(Code.error, "请上传" + width + "*" + height + "的图片!"));
		//			}
		//			else if (type == 1)//大于等于指定宽度
		//			{
		//				if (image.Width < width || image.Height < height)
		//					return Json(new ResultMsg(Code.error, "请上传大于等于" + width + "*" + height + "的图片!"));
		//			}
		//			else if (type == 2)//固定宽度
		//			{
		//				if (image.Width != width)
		//					return Json(new ResultMsg(Code.error, "请上传宽度等于" + width + "高度不限的图片!"));
		//			}
		//		}
		//		string base64 = Convert.ToBase64String(bt);
		//		string param = JsonConvert.SerializeObject(new
		//		{
		//			code = string.IsNullOrEmpty(code) ? DateTime.Now.Ticks.ToString() : code
		//			,
		//			base64 = base64,
		//			name = Path.GetFileNameWithoutExtension(file.FileName)
		//			,
		//			prefix = prefixName
		//			,
		//			extension = UploadHelper.GetExtension(file.FileName)
		//			,
		//			folder = folderName.Equals("logo") ? "gj" : folderName
		//		});
		//		var result = UploadHelper.UploadFile(ConfigHelper.Config.ImageUpload, param);
		//		if (result != null)
		//			return Json(new ResultMsg<dynamic>(Code.success, "上传成功", new { filename = result.name, filepath = result.url, base64 = base64 }, 0));
		//		else
		//			return Json(new ResultMsg(Code.error, "上传失败，请重试!"));
		//	}
		//	catch (Exception ex)
		//	{
		//		return Json(new ResultMsg(Code.error, "上传失败，请重试!"));
		//	}
		//}



	}
}
